package com.gzhryc.shared_device.oem.h5.mng.controllers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;

import com.gzhryc.common.ImageTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.data.dto.TreeResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.EncryptTools;
import com.gzhryc.dictionary.dao.db.CountryArea;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.servlet.upload.UploadFiles;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.oem.code.ResourceAPIServer;
import com.gzhryc.shared_device.oem.code.config.dao.db.LogisticsCompany;
import com.gzhryc.shared_device.oem.code.config.dao.enums.LogisticsCompanyEnum;
import com.gzhryc.shared_device.oem.code.config.services.LogisticsCompanyService;
import com.gzhryc.shared_device.oem.code.config.services.dto.LogisticsCompanySearch;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.mng.dto.ImageUploadResponse;

public class CommonController {
	
	static Logger log = Logger.getLogger(CommonController.class);

    /**
     * 获取中国地区树结构
     *
     * @param request
     * @param response
     * @return
     */
    @Route("/common/china/area/tree/select.data")
    public TreeResult<CountryArea> select(HttpServletRequest request, HttpServletResponse response) {
        TreeResult<CountryArea> result = new TreeResult<CountryArea>(DtoConstants.SUCCESS);
        List<CountryArea> data = CountryAreaUtils.getCountryAreaList();
        result.getBody().setData(data);
        return result;
    }

    @Route("/common/logistics_company/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        LogisticsCompanySearch search = new LogisticsCompanySearch();
        search.setName(term);
        search.setMaxState(LogisticsCompanyEnum.State.Default.index());
        Long total = 0L;
        List<LogisticsCompany> list = LogisticsCompanyService.self().findBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (LogisticsCompany logisticsCompany : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(logisticsCompany.getId());
                item.setText(logisticsCompany.getName());
                result.getBody().getData().add(item);
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
    
    @Route(value = {"/common/place/img/upload.do"})
    public ImageUploadResponse uploadPlaceImg(HttpServletRequest request, UploadFiles uploadFiles) {
        ImageUploadResponse result = new ImageUploadResponse(DtoConstants.EXECUTE_ERROR, "上传失败，请稍后再试");
        FileItem fileItem = uploadFiles.getFirstFile();
        if (fileItem != null) {
            try {
                String extension = FilenameUtils.getExtension(fileItem.getName());
                if("webp".equals(extension)){
                    extension = "jpg";
                }
                
                //检查是否是本地资源
                boolean localRes = PropertyTools.get().getBoolean("localRes",false);
                if(localRes) {
                	String localDir = PropertyTools.get().getString("localDir","");
                	String filePath =  ResourceAPIServer.placePath + "/" + EncryptTools.md5(UUID.randomUUID() + fileItem.getName()) + "." + extension;
                	//保存到本地资源文件里
                	String path = PropertyTools.get().getString("localResPath") + localDir + filePath;
	                File file = new File(path);
	                if(!file.getParentFile().exists()) {
	                	file.getParentFile().mkdirs();
	                }
	                fileItem.write(file);
	                
	                BufferedImage image = ImageIO.read(file);		//图片格式不正确读取或NULL
	                if(image != null) {
	                	//压缩
	                	BufferedImage thumbnailImg = ImageTools.thumbnailAndCropping(image,ResourceAPIServer.placeThumbWidth,ResourceAPIServer.placeThumbHeight);
	                	ImageIO.write(thumbnailImg, "jpg", file);
	                }
                	
	                result.setCode(DtoConstants.SUCCESS, null);
                    result.getBody().setPath(filePath);
                    result.getBody().setImgUrl(request.getServletContext().getContextPath() + localDir + filePath);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            result.setMsg("获取图片信息失败");
        }
        return result;
    }
    
    @Route(value = {"/common/device/img/upload.do"})
    public ImageUploadResponse uploadDeviceImg(HttpServletRequest request, UploadFiles uploadFiles) {
        ImageUploadResponse result = new ImageUploadResponse(DtoConstants.EXECUTE_ERROR, "上传失败，请稍后再试");
        FileItem fileItem = uploadFiles.getFirstFile();
        if (fileItem != null) {
            try {
                String extension = FilenameUtils.getExtension(fileItem.getName());
                if("webp".equals(extension)){
                    extension = "jpg";
                }
                
                //检查是否是本地资源
                boolean localRes = PropertyTools.get().getBoolean("localRes",false);
                if(localRes) {
                	String localDir = PropertyTools.get().getString("localDir","");
                	String filePath =  ResourceAPIServer.devicePath + "/" + EncryptTools.md5(UUID.randomUUID() + fileItem.getName()) + "." + extension;
                	//保存到本地资源文件里
                	String path = PropertyTools.get().getString("localResPath") + localDir + filePath;
	                File file = new File(path);
	                if(!file.getParentFile().exists()) {
	                	file.getParentFile().mkdirs();
	                }
	                fileItem.write(file);
	                
	                BufferedImage image = ImageIO.read(file);		//图片格式不正确读取或NULL
	                if(image != null) {
	                	//压缩
	                	BufferedImage thumbnailImg = ImageTools.thumbnailAndCropping(image,ResourceAPIServer.deviceThumbWidth,ResourceAPIServer.deviceThumbHeight);
	                	ImageIO.write(thumbnailImg, "jpg", file);
	                }
                	
	                result.setCode(DtoConstants.SUCCESS, null);
                    result.getBody().setPath(filePath);
                    result.getBody().setImgUrl(request.getServletContext().getContextPath()+ localDir + filePath);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            result.setMsg("获取图片信息失败");
        }
        return result;
    }

    @Route(value = {"/common/icon/img/upload.do"})
    public ImageUploadResponse uploadIconImg(HttpServletRequest request, UploadFiles uploadFiles) {
        ImageUploadResponse result = new ImageUploadResponse(DtoConstants.EXECUTE_ERROR, "上传失败，请稍后再试");
        FileItem fileItem = uploadFiles.getFirstFile();
        if (fileItem != null) {
            try {
                String extension = FilenameUtils.getExtension(fileItem.getName());
                if("webp".equals(extension)){
                    extension = "jpg";
                }
                
                //检查是否是本地资源
                boolean localRes = PropertyTools.get().getBoolean("localRes",false);
                if(localRes) {
                	String localDir = PropertyTools.get().getString("localDir","");
                	String filePath =  ResourceAPIServer.iconPath + "/" + EncryptTools.md5(UUID.randomUUID() + fileItem.getName()) + "." + extension;
                	//保存到本地资源文件里
                	String path = PropertyTools.get().getString("localResPath") + localDir + filePath;
	                File file = new File(path);
	                if(!file.getParentFile().exists()) {
	                	file.getParentFile().mkdirs();
	                }
	                fileItem.write(file);
	                
	                BufferedImage image = ImageIO.read(file);		//图片格式不正确读取或NULL
	                if(image != null) {
	                	//压缩
	                	BufferedImage thumbnailImg = ImageTools.thumbnailAndCropping(image,ResourceAPIServer.placeThumbWidth,ResourceAPIServer.placeThumbHeight);
	                	ImageIO.write(thumbnailImg, "jpg", file);
	                }
                	
	                result.setCode(DtoConstants.SUCCESS, null);
                    result.getBody().setPath(filePath);
                    result.getBody().setImgUrl(request.getServletContext().getContextPath() + localDir + filePath);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            result.setMsg("获取图片信息失败");
        }
        return result;
    }
}
